package com.tuozixuan.filter;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

public class IpFilter extends ZuulFilter {
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    private List<String> blackIpList = Arrays.asList("127.0.0.1");

    /**
     * 是否執行該過濾器，true為執行，false為不執行
     */
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        Object isSuccess = requestContext.get("isSuccess");
        return isSuccess == null ? true : Boolean.parseBoolean(isSuccess.toString());
    }

    /**
     * 執行自己的業務邏輯
     */
    public Object run() throws ZuulException {
        logger.info("IpFilter run start...");
        RequestContext requestContext = RequestContext.getCurrentContext();
        System.out.println(1/0);
        String ip = "127.0.0.2"; // TODO 從requestContext中獲取IP
        if (StringUtils.isNotBlank(ip) && blackIpList.contains(ip)) {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseBody("error");
            requestContext.getResponse().setContentType("application/json;charset=utf-8");
            requestContext.set("isSuccess", false); 
            return null;
        }
        
        requestContext.set("ip", ip); // 過濾器中傳遞數據
        logger.info("IpFilter run end...");
        return null;
    }

    /**
     * 過濾器類型，可選值為pre、route、post、error
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 過濾器的執行順序，數值越小，優先級越高
     */
    @Override
    public int filterOrder() {
        return 1;
    }
    
}
